﻿using HP.UtilsLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using XiaoweiUWP.Helper;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace XiaoweiUWP.Pags
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class ScanPage : Page
    {
        public ScanPage()
        {
            this.InitializeComponent();
        }
        private async void QrCodeChanged(string filepath)
        {
            var stream = await FileHelper.ToRandomAccessStreamAsync(filepath).ConfigureAwait(false);
            if (stream != null)
            {
                await Run.Invoke(Dispatcher, async () =>
                {
                    BitmapImage image = new BitmapImage();
                    await image.SetSourceAsync(stream);
                    QrCode.Source = image;
                    timer.Start();
                    timer2.Stop();
                    LoadingPic.Visibility = Visibility.Collapsed;
                    QrCode.Visibility = Visibility.Visible;
                    ErrorPic.Visibility = Visibility.Collapsed;
                }).ConfigureAwait(false);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // XiaoweiAI.Instance.QrCodeChanged += QrCodeChanged;
            Services.AppServiceManager.Instance.RegisterFunction("QrCodeChanged", (vset) =>
            {
               
                var path=vset["path"].ToString();
                QrCodeChanged(path);
                return null;
            });
            timer.Tick += Timer_Tick;
            timer.Interval = TimeSpan.FromHours(1);
            timer2.Tick += Timer2_Tick;
            timer2.Interval = TimeSpan.FromSeconds(5);
            RefreshQR();
        }

        private void Timer2_Tick(object sender, object e)
        {
            timer2.Stop();
            ShowError();
        }

        private void Timer_Tick(object sender, object e)
        {
            timer.Stop();
            RefreshQR();
        }

        private void ShowLoading()
        {
            _=Run.Invoke(Dispatcher, async () =>
            {
                LoadingPic.Visibility = Visibility.Visible;
                QrCode.Visibility = Visibility.Collapsed;
                ErrorPic.Visibility = Visibility.Collapsed;
            });
        }

        private void ShowError()
        {
           _= Run.Invoke(Dispatcher, async () =>
            {
                LoadingPic.Visibility = Visibility.Collapsed;
                QrCode.Visibility = Visibility.Collapsed;
                ErrorPic.Visibility = Visibility.Visible;
            });
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // XiaoweiAI.Instance.QrCodeChanged -= QrCodeChanged;
           
            timer.Tick -= Timer_Tick;
            timer2.Tick -= Timer2_Tick;
            timer.Stop();
            timer2.Stop();
        }

        DispatcherTimer timer = new DispatcherTimer();
        DispatcherTimer timer2 = new DispatcherTimer();
        private void BtnClick_Refresh(object sender, PointerRoutedEventArgs e)
        {
         //  _ = HPMetrics.Metrics.Track(XiaoweiAI.Instance.UserId, (int)HPMetrics.XwEventType.ClickButton, "LoginPageRefresh");
            RefreshQR();
        }

        private void RefreshQR()
        {
            // XiaoweiAI.Instance.RequestQrCodeUpdate();
             Services.AppServiceManager.Instance.SendMessage(new ValueSet { { "Request", "RequestQrCodeUpdate" } });
            ShowLoading();
            timer2.Start();
        }
    }
}
